using UnityEngine;
using System;
using System.IO;
using System.Text;

public class LogManager : MonoBehaviour
{
    private static LogManager instance;
    private string logFilePath;
    private StreamWriter logWriter;
    private bool isInitialized = false;

    public static LogManager Instance
    {
        get
        {
            if (instance == null)
            {
                GameObject go = new GameObject("LogManager");
                instance = go.AddComponent<LogManager>();
                DontDestroyOnLoad(go);
            }
            return instance;
        }
    }

    void Awake()
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
            InitializeLogger();
        }
        else if (instance != this)
        {
            Destroy(gameObject);
        }
    }

    private void InitializeLogger()
    {
        try
        {
            // 获取程序安装目录
            string appPath = Path.GetDirectoryName(Application.dataPath);
            if (string.IsNullOrEmpty(appPath))
            {
                Debug.LogError("无法获取程序安装目录，改用%userprofile%\\AppData\\LocalLow\\[公司名]\\[项目名]\\Logs");
                // 在 Application.persistentDataPath 下创建 Logs 文件夹
                appPath = Application.persistentDataPath;
            }

            // 在程序安装目录下创建 Logs 文件夹
            string logDirectory = Path.Combine(appPath, "Logs");
            if (!Directory.Exists(logDirectory))
            {
                Directory.CreateDirectory(logDirectory);
            }

            // 使用当前日期作为日志文件名
            string dateTime = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
            logFilePath = Path.Combine(logDirectory, $"game_log_{dateTime}.txt");

            // 创建或打开日志文件
            logWriter = new StreamWriter(logFilePath, true, Encoding.UTF8);
            isInitialized = true;

            // 注册日志回调
            Application.logMessageReceived += HandleLog;

            // 写入初始日志信息
            WriteLog($"=== 玩法日志开始于 {DateTime.Now} ===");
            WriteLog($"Unity版本: {Application.unityVersion}");
            WriteLog($"操作系统: {SystemInfo.operatingSystem}");
            WriteLog($"设备型号: {SystemInfo.deviceModel}");
            WriteLog($"日志文件路径: {logFilePath}");
        }
        catch (Exception e)
        {
            Debug.LogError($"初始化日志系统失败: {e.Message}");
        }
    }

    private void HandleLog(string logString, string stackTrace, LogType type)
    {
        if (!isInitialized) return;

        try
        {
            string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            string logMessage = $"[{timestamp}] [{type}] {logString}";
            
            // 如果是错误或异常，添加堆栈跟踪
            if (type == LogType.Error || type == LogType.Exception)
            {
                logMessage += $"\nStack Trace:\n{stackTrace}";
            }

            // 写入文件
            logWriter.WriteLine(logMessage);
            logWriter.Flush(); // 确保立即写入文件
        }
        catch (Exception e)
        {
            Debug.LogError($"写入日志失败: {e.Message}");
        }
    }

    private void WriteLog(string message)
    {
        if (!isInitialized) return;

        try
        {
            string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            string logMessage = $"[{timestamp}] {message}";
            
            // 写入文件
            logWriter.WriteLine(logMessage);
            logWriter.Flush(); // 确保立即写入文件
        }
        catch (Exception e)
        {
            Debug.LogError($"写入日志失败: {e.Message}");
        }
    }

    void OnApplicationQuit()
    {
        if (isInitialized)
        {
            WriteLog("=== 玩法日志结束 ===");
            Application.logMessageReceived -= HandleLog;
            if (logWriter != null)
            {
                logWriter.Close();
                logWriter = null;
            }
        }
    }

    void OnDestroy()
    {
        if (isInitialized)
        {
            Application.logMessageReceived -= HandleLog;
            if (logWriter != null)
            {
                logWriter.Close();
                logWriter = null;
            }
        }
    }
} 